package com.zdkj.common.core.exceltools;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.common.core.exceltools
 * @ClassName: DbHelper
 * @Description: 添加注解sql方法，为了简化方法，故暂时使用JDBC的方式
 * @Author: kangjian
 * @CreateDate: 2020/2/26 19:57
 * @Version: 1.0
 */
@Service
@Slf4j
public class DbHelper {

    @Autowired
    private DataSource dataSource;

    public String selectByExceltools(String colsql,String value){
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        String oldValue;
        try {
            conn = dataSource.getConnection();
            stmt = conn.prepareStatement(colsql);
            stmt.setString(1, value);
            rs = stmt.executeQuery();
            if (!rs.next()) {
                //没有此类型数据，需要初始化
                return value;
            }
            oldValue = rs.getString(1);
        }catch (SQLException e) {
            oldValue=value;
            log.error("",e);
        } finally {
            closeQuietly(rs);
            closeQuietly(stmt);
            closeQuietly(conn);
        }
        return oldValue;
    }

    private static void closeQuietly(AutoCloseable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (Throwable e) {
                //Ignore
            }
        }
    }

}
